//
//  TrainingViewModel.swift
//  Fitness
//
//  Created by duanwenpu on 2021/9/9.
//

import Foundation
import SwiftUI

var WeekTraining: [EveryDayTrainingModel] = load()

private let FilePath : String = NSHomeDirectory() + "/Documents/WeakTraining.json"

func load() -> Array<EveryDayTrainingModel> {
    createSql()
    if getdata().count > 0 {
        return getdata()
    }
    return []
}
func getdata() -> Array<EveryDayTrainingModel> {
    var tempArray: Array<EveryDayTrainingModel> = [EveryDayTrainingModel]()
    let sql = "SELECT * FROM plan_table;"
    let db = SQLiteManager.getInstance().db
    if db.open() {
        if let resustSet = db.executeQuery(sql, withArgumentsIn: [])  {
            while resustSet.next() {
                 
              let idParameter = (resustSet.int(forColumn: "id"))
                let everyDayTrainingModel = resustSet.data(forColumn: "everyDayTrainingModel")
                let model = try! JSONDecoder().decode(EveryDayTrainingModel.self, from: everyDayTrainingModel!)
                print(idParameter,model as Any,resustSet.columnCount)
                tempArray.append(model)
            }
        }
    } else {
        print("ERROR AT \(db.lastError())")
    }
    db.close()
        return tempArray
}
func createSql() -> Void {
    let sql = "create table if not exists plan_table (everyDayTrainingModel BLOB NOT NULL);"
          let db = SQLiteManager.getInstance().db
          if db.open(){
                db.executeUpdate(sql, withArgumentsIn: [])
          } else{
              print("ERROR AT \(db.lastError())")
          }
          db.close()

}
var fn = {
    (v1: String) -> Void in
    return
    
}

func saveSql(_ object: EveryDayTrainingModel,_ completion: (_ v1: String)-> Void) -> Void{
    if object.trainingGroupArray.count <= 0  {
     completion("还没有添加计划，不能保存哦")
        return
    }
       let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        let data = try! encoder.encode(object)
//        let data = try! JSONSerialization.data(withJSONObject: object,
//                                            options: JSONSerialization.WritingOptions.prettyPrinted)
    let sql = "insert into plan_table (everyDayTrainingModel) values(?);"
    let ary = [data] as [Any]
         let db = SQLiteManager.getInstance().db
         if db.open() {
 
        db.executeUpdate(sql, withArgumentsIn: ary)
//             print("数据写入结果: \(db.executeUpdate(sql, withArgumentsIn: ary))")
             completion("保存成功")

         } else{
             print("ERROR AT \(db.lastError())")
         }
         db.close()
}

/// 修改已有数据
func updateSql(_ object: EveryDayTrainingModel) -> Void {
    let encoder = JSONEncoder()
     encoder.outputFormatting = .prettyPrinted
     let data = try! encoder.encode(object)
    let sql = "update into plan_table (everyDayTrainingModel) values(?);"
    let ary = [data] as [Any]
         let db = SQLiteManager.getInstance().db
         if db.open() {
 
        db.executeUpdate(sql, withArgumentsIn: ary)
//             print("数据写入结果: \(db.executeUpdate(sql, withArgumentsIn: ary))")

         } else{
             print("ERROR AT \(db.lastError())")
         }
         db.close()
}

func convert2Dict<T>(_ any: T) -> Any {
    let mirror = Mirror(reflecting: any)

    if let style = mirror.displayStyle {
        if style == .collection {
            var array: [Any] = []
            for (_, valueMaybe) in mirror.children {
                let value = unwrap(valueMaybe)
                array.append(convert2Dict(value))
            }
            return array
        } else {
            var dict: [String: Any] = [:]
            for (labelMaybe, valueMaybe) in mirror.children {
                guard let label = labelMaybe else { continue }
                let value = unwrap(valueMaybe)
                dict[label] = convert2Dict(value)
            }
            return dict
        }
    } else {
        return any
    }
}

func unwrap<T>(_ any: T) -> Any
{
    let mirror = Mirror(reflecting: any)
    guard mirror.displayStyle == .optional, let first = mirror.children.first else {
        return any
    }
    return first.value
}
